package com.sharedprint.system.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.alibaba.fastjson.JSON;

@WebServlet("/FileServlet")
public class FileServlet extends HttpServlet {

	/**
	 * 文件上传
	 */
	private static final long serialVersionUID = 8551707079930570538L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String action = req.getParameter("action");
		if (action.trim().equals("addUserHeadPic") && action != null) {
			try {
				addFile(req, resp);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (action.trim().equals("uploadDevImage1") && action != null) {
			try {
				addPicture(req, resp);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if (action.trim().equals("addGoodsPic") && action != null) {
			try {
				addPicture(req, resp);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		} 
		else {
			System.out.println("请上传action参数或核对action的参数值!");
		}
	}

	/**
	 * 添加商品图片
	 * 
	 * @param req
	 * @param resp
	 * @throws FileUploadException 
	 * @throws IOException 
	 */
	private void addPicture(HttpServletRequest req, HttpServletResponse resp) throws FileUploadException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload fileUpload = new ServletFileUpload(factory);
		List<FileItem> fileList = fileUpload.parseRequest(req);
		String fileName = null;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");
		for (FileItem fileItem : fileList) {
			if (fileItem.getName() != null && !"".equals(fileItem.getName().trim())) {
				System.out.println(fileItem.getFieldName() + "," + fileItem.getName());
				String realPath = req.getServletContext().getRealPath("/");
				fileName = fileItem.getName();
				// 判断上传的文件是绝对路径还是一个文件名字
				if (fileName.indexOf('\\') != -1) // 路径是否存在‘/’
				{
					String[] fileNameArry = null;
					fileNameArry = fileName.split("\\\\");
					int max = fileNameArry.length;
					fileName = fileNameArry[max - 1];
					System.out.println("提取后的fileName=" + fileName);
				}
				OutputStream os = new FileOutputStream(new File(realPath + "/" + fileName));
				IOUtils.copy(fileItem.getInputStream(), os);

			}
		}
		if (fileName != null && !"".equals(fileName)) {
			System.out.println("fileName:" + fileName);
			resultMap.put("success", "1");
			resultMap.put("fileName", fileName);
			String[] str = fileName.split("\\.");
			String fileType = str[1];
			System.err.println("fileType="+fileType);
			resultMap.put("fileType", fileType);
		} else {
			resultMap.put("msg", "请上传文件!");
		}
		String result = JSON.toJSONString(resultMap);
		System.out.println("result=" + result);
		resp.getWriter().print(result);

	}

	/**
	 * 添加文件 并返回文件名
	 * 
	 * @param req
	 * @param resp
	 * @throws FileUploadException
	 * @throws IOException
	 */
	private void addFile(HttpServletRequest req, HttpServletResponse resp) throws FileUploadException, IOException {

		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload fileUpload = new ServletFileUpload(factory);
		List<FileItem> fileList = fileUpload.parseRequest(req);
		String fileName = null;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");
		for (FileItem fileItem : fileList) {
			if (fileItem.getName() != null && !"".equals(fileItem.getName().trim())) {
				System.out.println(fileItem.getFieldName() + "," + fileItem.getName());
				String realPath = req.getServletContext().getRealPath("/");
				fileName = fileItem.getName();
				// 判断上传的文件是绝对路径还是一个文件名字
				if (fileName.indexOf('\\') != -1) // 路径是否存在‘/’
				{
					String[] fileNameArry = null;
					fileNameArry = fileName.split("\\\\");
					int max = fileNameArry.length;
					fileName = fileNameArry[max - 1];
					System.out.println("提取后的fileName=" + fileName);
				}
				OutputStream os = new FileOutputStream(new File(realPath + "/" + fileName));
				IOUtils.copy(fileItem.getInputStream(), os);

			}
		}
		if (fileName != null && !"".equals(fileName)) {
			System.out.println("fileName:" + fileName);
			resultMap.put("success", "1");
			resultMap.put("fileName", fileName);
		} else {
			resultMap.put("msg", "请上传文件!");
		}
		String result = JSON.toJSONString(resultMap);
		System.out.println("result=" + result);
		resp.getWriter().print(result);

	}

}
